<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

/**
 * App\Models\Cash
 *
 * @property int $id
 * @property int|null $user_id 用户id
 * @property string|null $money 提现金额
 * @property string|null $charged_money 提现手续费
 * @property int|null $type 提现账户类型（1：支付宝，2：银行卡，3：微信）
 * @property string|null $type_name 提现账户类型名称
 * @property string|null $account 提现账号
 * @property string|null $fail 提现失败原因
 * @property int|null $status 状态（0：提现中，1：提现成功，2：提现失败）
 * @property string|null $statusd_at 提现处理时间
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|Cash newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Cash newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Cash query()
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereAccount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereChargedMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereFail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereStatusdAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereTypeName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Cash whereUserId($value)
 * @mixin \Eloquent
 */
class Cash extends Base
{
    protected $table = 'cash';

    // 修改提现状态
    static function setStatus($id, $status, $fail=null)
    {
        try {
            DB::beginTransaction();

            $model = Cash::find($id);

            if ($model->status != 0) {
                throw new \Exception('状态错误');
            }

            $model->status = $status;
            $model->fail = $fail;
            $model->statusd_at = now();
            $model->save();

            if ($status == 2) {
                // 拒绝退还余额
                User::whereId($model->user_id)->increment('balance', $model->money);
            }
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
        } catch (\Throwable $e) {
            DB::rollBack();
        }
        return false;
    }
}
